package com.sk.rpcAssistNetty.io.protocol;

import lombok.Data;

import java.util.concurrent.ConcurrentHashMap;

/**
 * description：序列化协议管理(饿汉单例)
 *
 * @author 孙文斌
 * @Date: 2021/2/7 9:54
 */
@Data
public class ProtocolManage {
    final static HessianSerialize hessianSerialize = HessianSerialize.getInstance();
    final static JsonSerialization jsonSerialization = JsonSerialization.getInstance();

    private final ConcurrentHashMap<String, SerializeProtocol> messageProtocolMap = new ConcurrentHashMap();

    private static ProtocolManage protocolManage = new ProtocolManage();

    public static ProtocolManage getInstance() {
        return ProtocolManage.protocolManage;
    }

    private ProtocolManage() {
        loadPresetProtocol();
    }

    private final void loadPresetProtocol() {
        //加载所有预置的序列化协议
        messageProtocolMap.put(jsonSerialization.getCode(), jsonSerialization);
        messageProtocolMap.put(hessianSerialize.getCode(), hessianSerialize);
    }

    public final SerializeProtocol getProtocolByCode(String code) {
        return messageProtocolMap.get(code);
    }

    public final SerializeProtocol getDefaultProtocol() {
        return hessianSerialize;
    }

    public void add(SerializeProtocol protocol) {
        //code重复检查
        SerializeProtocol proto = messageProtocolMap.get(protocol.getCode());
        if (proto != null) {
            throw new RuntimeException("protocol already exsit");
        }
        messageProtocolMap.put(protocol.getCode(), protocol);
    }
}
